#!/usr/bin/env python 3.9
# -*- coding = utr-8 -*-
'''
@Project: mysite1
@File: views.py
@IDE: PyCharm
@Author: Simon
@Date: 5/8/21  5:14 AM
'''

from django.http import HttpResponse

from django.shortcuts import render


def page_2003_view(request):
    html = "<h1> First Page </h1>"

    return HttpResponse(html)


def index_view(request):
    html = "Index Page"
    return HttpResponse(html)


def page1_view(request):
    html = "Page 1"
    return HttpResponse(html)


def page2_view(request):
    html = "Page 2"
    return HttpResponse(html)


def pagen_view(request, pg):
    html = "Item %s." % (pg)

    return HttpResponse(html)


def test_request(request):
    print('path info is ', request.path_info)
    print('method is ', request.method)
    print('querystring is ', request.GET)

    return HttpResponse('test request ok')


POST_FORM = '''
<form method='post' action='/test_get_post'>
    Name: <input type='text' name='uname'>
    <input type='submit' value='Login'>
</form>
'''


def test_get_post(request):

    if request.method == 'GET':
        # print(request.GET['a'])
        print(request.GET.get('c', 'no c'))
        return HttpResponse(POST_FORM)
    elif request.method == 'POST':
        # do the function
        print('uname is ', request.POST['uname'])
        return HttpResponse('post is ok')
    else:
        pass

    return HttpResponse('--test get post is ok')


# template

def test_html(request):
    # Case 1
    # from django.template import loader
    # t = loader.get_template('test_html.html')
    # html = t.render()
    # return HttpResponse(html)

    # Case 2
    # from django.shortcuts import render
    dic = {
        'username': 'Simon'

    }
    return render(request, 'test_html.html', dic)


def test_if_for(request):
    dic = {}
    dic['x'] = 10
    dic['lst'] = ['Tom', 'Jack', 'Lily']
    return render(request, "test_if_for.html", dic)


def test_mycal(request):
    if request.method == 'GET':
        return render(request, "mycal.html")
    elif request.method == 'POST':
        # deal with cal
        x = int(request.POST['x'])
        y = int(request.POST['y'])
        op = request.POST['op']

        if op == 'add':
            result = x + y
        elif op == 'sub':
            result = x - y
        elif op == 'mul':
            result = x * y
        elif op == 'div':
            result = x / y

        # locals() equal to     帮我们封装函数中的局部变量为一个字典
        # dic = {'x':x, 'y':y, 'op':op}
        return render(request, "mycal.html", locals())


# extend html

def base_view(request):
    return render(request, 'base.html')


def music_view(request):
    return render(request, 'music.html')


def sport_view(request):
    return render(request, 'sport.html')


# url

def test_url(request):
    return render(request, 'test_url.html')


def test_url_result(request):
    return render(request, 'test_url_result.html')